import { ref } from "vue";
import { http } from "../http";
import { User } from "../interface/user.interface";

export function useUser() {
  const user = ref({} as User);

  const getUser = async () => {
    if (localStorage.token) {
      try {
        user.value = (await http.get(`/users/info`)).data;
      } catch (e) {
        localStorage.clear();
      }
    }
  };

  const updateUser = async (userModel: any) => {
    const { repassword, ...data } = userModel;
    if (localStorage.token) {
      try {
        user.value = (
          await http.patch(`/users/edit`, {
            ...data,
          })
        ).data;
      } catch (e) {
        localStorage.clear();
      }
    }
  };

  return {
    user,
    getUser,
    updateUser,
  };
}
